# pythonProject5/core/config.py

from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import computed_field, model_validator
from typing import Optional, List
from pathlib import Path

# 调试：打印 .env 路径 ---
BASE_DIR = Path(__file__).parent.parent.absolute()
ENV_FILE = BASE_DIR / ".env"

# 设置OpenMP环境变量以避免冲突
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"

class Settings(BaseSettings):
    # -------------------------------
    # 基础配置
    # -------------------------------
    BASE_DIR: Path = BASE_DIR
    UPLOAD_DIR: Path = BASE_DIR / "uploads"
    TEMP_DIR: Path = BASE_DIR / "temp"
    CACHE_DIR: Path = BASE_DIR / "cache"
    MODEL_CACHE_DIR: Path = CACHE_DIR / "models"

    # -------------------------------
    # 日志配置
    # -------------------------------
    LOG_LEVEL: str = "INFO"
    LOG_FILE: Optional[Path] = BASE_DIR / "logs" / "app.log"

    # -------------------------------
    # 文件上传配置
    # -------------------------------
    MAX_FILE_SIZE: int = 50 * 1024 * 1024  # 50MB

    # -------------------------------
    # 数据库配置
    # -------------------------------
    DATABASE_URL: str = "sqlite:///./data/database.db"
    DATABASE_POOL_SIZE: int = 5
    DATABASE_MAX_OVERFLOW: int = 10
    DATABASE_POOL_TIMEOUT: int = 30
    DATABASE_POOL_RECYCLE: int = 3600
    DATABASE_ECHO: bool = False

    # -------------------------------
    # 安全与认证
    # -------------------------------
    SECRET_KEY: str = "your-super-secret-key-change-in-prod"
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    REFRESH_TOKEN_EXPIRE_DAYS: int = 7

    # -------------------------------
    # 翻译服务配置
    # -------------------------------
    DEFAULT_SOURCE_LANG: str = "auto"
    DEFAULT_TARGET_LANG: str = "en"
    SUPPORTED_LANGUAGES: List[str] = ["zh", "en", "ja", "ko", "fr", "es", "ru", "de"]

    USE_REAL_TRANSLATION_MODEL: bool = True
    WHISPER_MODEL_PATH: Path = BASE_DIR / "models" / "whisper"  # 保持兼容旧名
    
    # 流式翻译配置
    STREAMING_TRANSLATION_ENABLED: bool = True
    STREAMING_CHUNK_DURATION: float = 2.0  # 默认流式翻译音频块时长（秒）

    # -------------------------------
    # ASR（语音识别）配置
    # -------------------------------
    ASR_ENGINE: str = "whisper"  # "whisper" 或 "paraformer"
    ASR_MODEL_NAME: str = "base"  # tiny, base, small, medium, large
    ASR_MODEL_ROOT_DIR: Path = BASE_DIR / "models" / "whisper"
    ASR_LANGUAGE: str = "zh"
    ASR_DEVICE: str = "cpu"  # "cpu" or "cuda"
    ASR_USE_LOCAL_MODEL: bool = True
    ASR_SAMPLE_RATE: int = 16000
    # 控制是否使用真实ASR引擎
    USE_REAL_ASR: bool = True  # ←← 关键！默认为 True，使用真实引擎
    
    # -------------------------------
    # Paraformer ASR 配置
    # -------------------------------
    PARAFORMER_MODEL_PATH: Path = BASE_DIR / "baseline_paraformer_conformer_12e_6d_2048_256_zh_char_exp1" / "model.pt.avg10"
    PARAFORMER_DEVICE: str = "cpu"  # "cpu" or "cuda"
    PARAFORMER_CONFIG_PATH: Path = BASE_DIR / "baseline_paraformer_conformer_12e_6d_2048_256_zh_char_exp1" / "config.yaml"
    # -------------------------------
    # 翻译模型配置（NMT 模型，如 Fairseq, MarianMT 等）
    # -------------------------------
    TRANSLATION_MODEL_PATH: Path = BASE_DIR / "models" / "translation"
    TRANSLATION_CONFIG_NAME: str = "config.yaml"
    TRANSLATION_MODEL_NAME: str = "model.pt"
    TRANSLATION_SOURCE_LANG: str = "auto"
    TRANSLATION_TARGET_LANG: str = "en"
    TRANSLATION_DEVICE: str = "cpu"

    # -------------------------------
    # API 服务配置
    # -------------------------------
    API_TITLE: str = "Audio Translation & ASR API"
    API_DESCRIPTION: str = "基于 FastAPI 构建的语音识别与翻译服务接口"
    API_VERSION: str = "1.0.0"
    API_PREFIX: str = "/api"

    # -------------------------------
    # 流式翻译配置
    # -------------------------------
    STREAMING_TRANSLATION_ENABLED: bool = True  # 是否启用流式翻译
    STREAMING_CHUNK_DURATION: float = 2.0  # 默认音频块时长（秒）
    STREAMING_MIN_CHUNK_SIZE: int = 1024  # 最小音频块大小（字节）
    
    # -------------------------------
    # 服务监听配置
    # -------------------------------
    HOST: str = "127.0.0.1"
    PORT: int = 8000
    DEBUG: bool = True

    # -------------------------------
    # 第三方 API 密钥
    # -------------------------------
    DEEPL_API_KEY: Optional[str] = None
    GOOGLE_TRANSLATE_KEY: Optional[str] = None

    # -------------------------------
    # 允许的音频 MIME 类型
    # -------------------------------
    ALLOWED_AUDIO_TYPES: List[str] = [
        "audio/mpeg",      # .mp3
        "audio/wav",
        "audio/x-wav",
        "audio/wave",
        "audio/x-wave",
        "audio/webm",      # .webm
        "audio/ogg",       # .ogg
        "audio/flac",      # .flac
        "audio/aac",       # .aac
        "audio/mp4",       # .m4a (e.g., m4a)
    ]

    # -------------------------------
    # 计算字段
    # -------------------------------
    @computed_field
    @property
    def REFRESH_TOKEN_EXPIRE_MINUTES(self) -> int:
        return self.REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60

    # -------------------------------
    # 模型验证器：路径初始化与目录创建
    # -------------------------------
    @model_validator(mode="after")
    def setup_directories(self) -> "Settings":
        """
        验证并创建所有必要目录
        注意：所有路径字段必须为 Path 类型
        """
        # 确保所有路径是绝对路径
        paths_to_ensure = [
            self.UPLOAD_DIR,
            self.TEMP_DIR,
            self.CACHE_DIR,
            self.MODEL_CACHE_DIR,
            self.ASR_MODEL_ROOT_DIR,
            self.TRANSLATION_MODEL_PATH,
            self.LOG_FILE.parent if self.LOG_FILE else None,
        ]

        # 过滤 None 并去重
        dirs_to_create = {p.absolute() for p in paths_to_ensure if p is not None}

        # 创建目录
        for path in dirs_to_create:
            path.mkdir(parents=True, exist_ok=True)

        return self

    # -------------------------------
    # Pydantic v2 配置
    # -------------------------------
    model_config = SettingsConfigDict(
        env_file=ENV_FILE,
        env_file_encoding="utf-8",
        case_sensitive=True,
        extra="ignore",  # 忽略多余字段
    )


# ===============================
# 全局实例
# ===============================
settings = Settings()


# -------------------------------
# 调试输出
# -------------------------------
if __name__ == "__main__":
    print(" 配置加载成功！")
    for key, value in settings.model_dump().items():
        print(f"  {key}: {value}")